import { io } from 'socket.io-client';

const PLAYER_TOKENS = ['4ab6d84a-fe23-4f14-9d7c-e49a5435e8c3'];
const _BASE_URL = 'https://tt2-public.gamehivegames.com';

class Connector {
  constructor() {
    // 假设 API_URL 是从环境变量或配置中获取的
    this.API_URL = 'wss://tt2-public.gamehivegames.com'; // 替换为实际的 API 地址
    this.AUTH_TOKEN = '';
  }

  raidRestConnect = () => {
    fetch(`${_BASE_URL}/raid/subscribe`, {
      method: 'post',
      headers: {
        'API-Authenticate': this.AUTH_TOKEN,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ player_tokens: PLAYER_TOKENS }),
    })
      .then(res => res.json())
      .then(res => {
        console.log('====');
        console.log(res);
      })
      .catch(e => {
        console.log('====');
        console.log(e);
      });
  };

  playerRestConnect = () => {
    fetch(`${_BASE_URL}/player/data`, {
      method: 'post',
      headers: {
        'API-Authenticate': this.AUTH_TOKEN,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ player_token: PLAYER_TOKENS[0], properties: ['titan_cards', 'cards'] }),
    })
      .then(res => res.json())
      .then(res => {
        console.log('====');
        console.log(res);
      })
      .catch(e => {
        console.log('====');
        console.log(e);
      });
  };

  connect = async auth => {
    // 创建 Socket.IO 客户端实例
    this.AUTH_TOKEN = auth;
    const commonOptions = {
      transports: ['websocket'],
      extraHeaders: { 'API-Authenticate': auth },
      path: '/api', // 对应 Python 中的 socketio_path
      autoConnect: false, // 不自动连接，等待手动调用 connect()
      reconnection: false, // 禁用自动重连，与 Python 代码行为一致
      timeout: 5000,
    };
    const raidIO = io(`${this.API_URL}/raid`, commonOptions);
    const playerIO = io(`${this.API_URL}/player`, commonOptions);

    // 等待连接成功的 Promise 封装
    const connectPromise = new Promise((resolve, reject) => {
      // 默认事件
      raidIO.on('connect', this.raidRestConnect);
      raidIO.on('error', error => {
        reject(new Error(`raidIO连接失败: ${error.message}`));
      });
      // TT2事件
      raidIO.on('connected', () => {
        console.log('!!!!connected!!!!');
      });
      raidIO.on('start', (data) => {
        console.log('!!!!start!!!!');
        console.log(data);
      });
      raidIO.on('sub_start', (data) => {
        console.log('!!!!sub_start!!!!');
        console.log(data);
      });
      raidIO.on('end', (data) => {
        console.log('!!!!end!!!!');
        console.log(data);
      });

      playerIO.on('connect', this.playerRestConnect);
      playerIO.on('error', error => {
        reject(new Error(`playerIO连接失败: ${error.message}`));
      });

      // 开始连接
      raidIO.connect();
      playerIO.connect();
    });

    // 等待连接完成
    await connectPromise;

    // 保持连接（类似 Python 的 wait() 方法）
    return new Promise(() => {
      // 当所有命名空间都断开时才会结束
      let disconnectedNamespaces = 0;
      const totalNamespaces = 1;

      const onNamespaceDisconnected = () => {
        disconnectedNamespaces++;
        if (disconnectedNamespaces === totalNamespaces) {
          // 所有连接都已断开，可以在这里处理清理逻辑
          console.log('所有命名空间连接已断开');
        }
      };

      raidIO.on('disconnect', onNamespaceDisconnected);
      // playerNamespace.on("disconnect", onNamespaceDisconnected);
    });
  };
}

// 使用示例
async function main() {
  const connector = new Connector();
  try {
    const authToken = 'e97b51bb-7ed4-4d39-b826-1a2c2f0d9e76';
    console.log('开始连接...');
    await connector.connect(authToken);
    console.log('所有命名空间连接成功并保持连接中...');
  } catch (error) {
    console.error('连接过程出错:', error);
  }
}

main();
